package controllers

import (
	"github.com/ahmetb/go-linq/v3"
	"goconfcenter/core/consts"
	"goconfcenter/core/enums"
	"goconfcenter/core/response"
	"goconfcenter/models"
	"goconfcenter/pkg/Util"
	"goconfcenter/pkg/snowflake"
	"goconfcenter/service"
	"goconfcenter/service/dto/bus"
	"goconfcenter/settings"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type BackendUserControllers struct {
}

func (c *BackendUserControllers) DataGrid(ctx *gin.Context) {
	params := new(bus.BackendUserQuery)
	if err := ctx.ShouldBindJSON(params); err != nil {
		zap.L().Error("请求参数异常", zap.Error(err))
		response.ErrorParam(ctx, "")
		return
	}
	data, total := service.BackendUserServiceInstance().PageByQuery(params)
	var pageData response.PageData
	pageData.Data = data
	pageData.Total = total
	response.Success(ctx, consts.CurdStatusOkMsg, pageData)
}
func (c *BackendUserControllers) AccountExists(ctx *gin.Context) {
	params := new(bus.BackendUserQuery)
	if err := ctx.ShouldBindJSON(params); err != nil {
		zap.L().Error("请求参数异常", zap.Error(err))
		response.ErrorParam(ctx, "")
		return
	}
	result := service.BackendUserServiceInstance().AccountExists(params)
	response.Success(ctx, consts.CurdStatusOkMsg, result)
	return
}
func (c *BackendUserControllers) Add(ctx *gin.Context) {
	userId := ctx.GetInt64("userId")
	user := new(models.BackendUser)
	if err := ctx.ShouldBindJSON(user); err != nil {
		zap.L().Error("请求参数异常", zap.Error(err))
		response.ErrorParam(ctx, "")
		return
	}
	loginUser := service.BackendUserServiceInstance().GetInfo(userId)
	user.ID = snowflake.GenID()
	user.Creator = loginUser.ID
	user.Updater = loginUser.ID
	user.CreateTime = time.Now()
	user.UpdateTime = time.Now()
	frontPwd, err := Util.RsaDecryptByBase64(user.UserPwd, settings.Conf.AppConfig.MyPrivateKey)
	if err != nil {
		response.Fail(ctx, consts.BusinessFail, consts.BusinessFailMsg, "密码解密失败，请联系管理员")
		return
	}
	pwd := Util.Md5Salt(string(frontPwd), user.UserPwdExt)
	user.UserPwd = pwd
	result := service.BackendUserServiceInstance().Insert(user)
	if result == nil {
		response.Fail(ctx, consts.BusinessFail, consts.BusinessFailMsg, "添加用户失败")
	} else {
		response.Success(ctx, consts.CurdStatusOkMsg, result.ID)
	}
	return
}
func (c *BackendUserControllers) Get(ctx *gin.Context) {
	id, _ := strconv.ParseInt(ctx.DefaultQuery("id", "0"), 10, 64)
	result := service.BackendUserServiceInstance().Get(id)
	response.Success(ctx, consts.CurdStatusOkMsg, result)
	return
}
func (c *BackendUserControllers) Edit(ctx *gin.Context) {
	userId := ctx.GetInt64("userId")
	user := new(models.BackendUser)
	if err := ctx.ShouldBindJSON(user); err != nil {
		zap.L().Error("请求参数异常", zap.Error(err))
		response.ErrorParam(ctx, "")
		return
	}
	oldUser := service.BackendUserServiceInstance().Get(user.ID)
	loginUser := service.BackendUserServiceInstance().GetInfo(userId)
	oldUser.UserName = user.UserName
	oldUser.RealName = user.RealName
	oldUser.AuthType = user.AuthType
	oldUser.IsLock = user.IsLock
	oldUser.Status = user.Status
	oldUser.Updater = loginUser.ID
	oldUser.UpdateTime = time.Now()
	frontPwd, err := Util.RsaDecryptByBase64(user.UserPwd, settings.Conf.AppConfig.MyPrivateKey)
	if err != nil {
		response.Fail(ctx, consts.BusinessFail, consts.BusinessFailMsg, "密码解密失败，请联系管理员")
		return
	}
	pwd := Util.Md5Salt(string(frontPwd), user.UserPwdExt)
	user.UserPwd = pwd
	result := service.BackendUserServiceInstance().Update(oldUser)
	if result {
		response.Success(ctx, consts.CurdStatusOkMsg, oldUser.ID)
	} else {
		response.Fail(ctx, consts.BusinessFail, consts.BusinessFailMsg, "编辑失败")
	}
	return
}

func (c *BackendUserControllers) Lock(ctx *gin.Context) {
	userId := ctx.GetInt64("userId")
	user := new(models.BackendUser)
	if err := ctx.ShouldBindJSON(user); err != nil {
		zap.L().Error("请求参数异常", zap.Error(err))
		response.ErrorParam(ctx, "")
		return
	}
	oldUser := service.BackendUserServiceInstance().Get(user.ID)
	loginUser := service.BackendUserServiceInstance().GetInfo(userId)
	oldUser.IsLock = enums.Yes.Value()
	oldUser.Updater = loginUser.ID
	oldUser.UpdateTime = time.Now()
	result := service.BackendUserServiceInstance().Update(oldUser)
	if result {
		response.Success(ctx, consts.CurdStatusOkMsg, oldUser.ID)
	} else {
		response.Fail(ctx, consts.BusinessFail, consts.BusinessFailMsg, "锁定失败")
	}
	return
}
func (c *BackendUserControllers) UnLock(ctx *gin.Context) {
	userId := ctx.GetInt64("userId")
	user := new(models.BackendUser)
	if err := ctx.ShouldBindJSON(user); err != nil {
		zap.L().Error("请求参数异常", zap.Error(err))
		response.ErrorParam(ctx, "")
		return
	}
	oldUser := service.BackendUserServiceInstance().Get(user.ID)
	loginUser := service.BackendUserServiceInstance().GetInfo(userId)
	oldUser.IsLock = enums.No.Value()
	oldUser.Updater = loginUser.ID
	oldUser.UpdateTime = time.Now()
	result := service.BackendUserServiceInstance().Update(oldUser)
	if result {
		response.Success(ctx, consts.CurdStatusOkMsg, oldUser.ID)
	} else {
		response.Fail(ctx, consts.BusinessFail, consts.BusinessFailMsg, "解锁失败")
	}
	return
}
func (c *BackendUserControllers) Delete(ctx *gin.Context) {
	userId := ctx.GetInt64("userId")
	Ids := new(bus.DeleteDto)
	if err := ctx.ShouldBindJSON(Ids); err != nil {
		zap.L().Error("请求参数异常", zap.Error(err))
		response.ErrorParam(ctx, "")
		return
	}
	ids := Util.StringToInt64(Ids.Ids)
	loginUser := service.BackendUserServiceInstance().GetInfo(userId)
	result := service.BackendUserServiceInstance().BathDelete(&ids, loginUser.ID)
	if result {
		for _, value := range ids {
			service.BackendUserServiceInstance().ClearBackendLoginUserInfo(value)
		}
		response.Success(ctx, consts.CurdStatusOkMsg, true)
	} else {
		response.Fail(ctx, consts.BusinessFail, consts.BusinessFailMsg, "批量删除失败")
	}
	return
}

func (c *BackendUserControllers) RoleDataGrid(ctx *gin.Context) {
	params := new(bus.RoleQuery)
	if err := ctx.ShouldBindJSON(params); err != nil {
		zap.L().Error("请求参数异常", zap.Error(err))
		response.ErrorParam(ctx, "")
		return
	}
	backendUser := service.BackendUserServiceInstance().Get(params.ID)
	if backendUser == nil {
		response.Fail(ctx, consts.BusinessFail, consts.BusinessFailMsg, "用户不存在")
		return
	}
	roleList := service.RoleServiceInstance().GetList()
	roleBackendUserRelList := service.GetRoleBackendUserRelServiceInstance().GetListByBackendUserId(backendUser.ID)
	for i, v := range roleList {
		one := linq.From(roleBackendUserRelList).WhereT(func(a *models.RoleBackendUserRel) bool {
			return v.ID == a.RoleId
		}).First()
		if one != nil {
			roleList[i].IsChecked = true
		}
	}
	var pageData response.PageData
	pageData.Data = roleList
	pageData.Total = int64(len(roleList))
	response.Success(ctx, consts.CurdStatusOkMsg, pageData)
	return
}
func (c *BackendUserControllers) AuthRole(ctx *gin.Context) {
	userId := ctx.GetInt64("userId")
	auth := new(bus.BackendUserAuthReq)
	if err := ctx.ShouldBindJSON(auth); err != nil {
		zap.L().Error("请求参数异常", zap.Error(err))
		response.ErrorParam(ctx, "")
		return
	}
	authIds := Util.StringToInt64(auth.AuthIds)
	result := service.GetRoleBackendUserRelServiceInstance().SaveRel(auth.ID, authIds, userId)
	response.Success(ctx, consts.CurdStatusOkMsg, result)
	return
}
